package com.framewiki.gpt.service.impl;

import com.cdkjframework.config.CustomConfig;
import com.cdkjframework.constant.IntegerConsts;
import com.cdkjframework.exceptions.GlobalRuntimeException;
import com.cdkjframework.util.encrypts.JwtUtils;
import com.cdkjframework.util.encrypts.Md5Utils;
import com.cdkjframework.util.network.http.HttpServletUtils;
import com.cdkjframework.util.tool.StringUtils;
import com.framewiki.gpt.config.ChatConfiguration;
import com.framewiki.gpt.dto.request.CreateChatCompletionDto;
import com.framewiki.gpt.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: framewiki-gpt
 * @Package: com.framewiki.gpt.service.impl
 * @ClassName: TokenServiceImpl
 * @Description: java类作用描述
 * @Author: xiaLin
 * @Date: 2023/6/21 23:46
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class TokenServiceImpl implements TokenService {

  /**
   * 配置
   */
  private final CustomConfig customConfig;

  /**
   * 配置
   */
  private final ChatConfiguration configuration;

  /**
   * 获取受权
   *
   * @param content 请求内容
   * @param token   受权信息
   * @return 返回结果
   */
  @Override
  public String getToken(CreateChatCompletionDto content, String token) {
    HttpServletResponse response = HttpServletUtils.getResponse();
    if (StringUtils.isNullAndSpaceOrEmpty(token) ||
        !configuration.getAppKey().equals(token)) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      throw new GlobalRuntimeException("token 错误！");
    }

    if (StringUtils.isNullAndSpaceOrEmpty(content.getModel())) {
      content.setModel(model);
    }
    LocalDateTime localDateTime = LocalDateTime.now().plusMonths(IntegerConsts.THREE);
    long expiration = localDateTime.toInstant(ZoneOffset.UTC).toEpochMilli();

    StringBuilder builder = new StringBuilder();
    builder.append(String.format("user=%s&effective=%s&time=%s&appKey=%s", content.getUser(), IntegerConsts.THREE, expiration,configuration.getAppKey()));
    String md5Token = Md5Utils.getMd5(builder.toString());
    // 加密数据
    Map<String, Object> map = new HashMap<>(IntegerConsts.THREE);
    map.put("user", content.getUser());
    map.put("token", md5Token);
    map.put("time", expiration);

    return JwtUtils.createJwt(map, customConfig.getJwtKey(), expiration);
  }
}
